package com.zerowidth.moc.web.utils;

import com.alibaba.fastjson.JSONObject;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpMethod;

import java.io.*;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

public class HttpUtils {

    /**
     * 将URL的参数和body参数合并
     */
    public static SortedMap<String, String> getAllParams(HttpServletRequest request) throws IOException {
        SortedMap<String, String> result = new TreeMap<>();


        //获取 url 上的参数
        Map<String, String> urlParams = getUrlParams(request);
        //保存 url 的参数
        for (Map.Entry<String, String> entry : urlParams.entrySet()) {
            result.put(entry.getKey(), entry.getValue());
        }


        Map<String, String> bodyRequestParam = new HashMap<>();
        //获取body上的参数
        if (false) {
            if (StringUtils.equals(HttpMethod.GET.name(), request.getMethod())) {
                // get请求不需要拿body参数
            } else {
                bodyRequestParam = getBodyRequestParam(request);
            }
        }
        //保存body参数
        for (Map.Entry<String, String> entry : bodyRequestParam.entrySet()) {
            result.put(entry.getKey(), entry.getValue());
        }
        return result;
    }

    /**
     * 获取 Body 参数
     */
    public static Map<String, String> getBodyRequestParam(final HttpServletRequest request) throws IOException {

        BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
        String str = "";
        StringBuilder wholeStr = new StringBuilder();
        //一行一行的读取body体里面的内容；
        while ((str = reader.readLine()) != null) {
            wholeStr.append(str);
        }
        //转化成json对象
        Map<String, String> map = new HashMap<>();
        return JSONObject.parseObject(wholeStr.toString(), map.getClass());
    }

    /**
     * 将URL请求参数转换成Map
     */
    public static Map<String, String> getUrlParams(HttpServletRequest request) {

        String param = "";
        try {
            String queryString = request.getQueryString();
            if (queryString != null) {
                param = URLDecoder.decode(queryString, "utf-8");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Map<String, String> result = new HashMap<>(16);
        String[] params = param.split("&");
        for (String s : params) {
            if (StringUtils.isNotEmpty(s)) {
                int index = s.indexOf("=");
                result.put(s.substring(0, index), s.substring(index + 1));
            }
        }
        return result;
    }

    /**
     * 读取 request body 内容作为字符串
     */
    public static String readRequest(HttpServletRequest request) throws IOException {
        InputStream inputStream;
        StringBuffer sb = new StringBuffer();
        inputStream = request.getInputStream();
        String str;
        BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        while ((str = in.readLine()) != null) {
            sb.append(str);
        }
        in.close();
        inputStream.close();
        return sb.toString();
    }

}